package huoye.shops.huoye.user.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.VpnService;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;


import com.codeideology.android.utils.AssetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.base.UserManager;
import huoye.shops.huoye.user.model.AreaInfo;
import huoye.shops.huoye.user.model.Province;
import huoye.shops.huoye.user.model.SelectCityData;
import huoye.shops.huoye.user.model.User;
import huoye.shops.huoye.user.presenter.SelectCityPresenter;
import huoye.shops.huoye.user.view.ISelectCityView;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static okhttp3.internal.Internal.instance;


public class SelectCityActivity extends BaseActivity implements ISelectCityView,EasyPermissions.PermissionCallbacks{


    @BindView(R.id.sp_province)
    Spinner spProvince;
    @BindView(R.id.sp_city)
    Spinner  spCity;
    @BindView(R.id.sp_area)
    Spinner  spArea;
    @BindView(R.id.tv_select_city)
    TextView tvSelectCity;
    private SelectCityPresenter mSelectCityPresenter;

    @OnClick(R.id.btn_ok)
    void onOkClick(){
        Log.e("test",provinceName+cityName+areaName);
        mSelectCityPresenter.selectCity(provinceName,cityName,areaName);
    }


    private ArrayAdapter<String> cityAdapter;
    private ArrayAdapter<String> areaAdapter;

    private List<Province> provinces = new ArrayList<>();     //所有省份的list

    private List<String> provinceList = new ArrayList<>(); // 所有省份的list
    private List<String> cityList = new ArrayList<>();     // 当前选中省份的城市
    private List<String> areaList = new ArrayList<>();     // 当前选中城市的城区

    private String provinceName;    // 省的名字
    private String cityName;        // 市的名字
    private String areaName;        // 区的名字

    private int provincePosition = 0; // 当前选的省份的位置
    private int cityPosition = 0;     // 当前城市在List中的位置
    private int areaPosition = 0;     // 当前城区在list的位置

    @Override
    protected int getContentViewId() {
        return R.layout.activity_select_city;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        String json = getJson("citylist.json", this);
        Type listType = new TypeToken<List<Province>>() {
        }.getType();
        //这里的json是字符串类型 = jsonArray.toString();
        provinces = new Gson().fromJson(json, listType );


        showData();
        //setInitSp();
        mSelectCityPresenter = new SelectCityPresenter();
        mSelectCityPresenter.addTaskListener(this);
        mSelectCityPresenter.onStart();
        openPower();

    }



    public static String getJson(String fileName,Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }





    /**
     * 展示数据
     */
    private void showData() {
        for (Province province : provinces) {
            provinceList.add(province.getName());
        }
        // 显示省份数据
        spProvince.setAdapter(new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, provinceList));
        spProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                provincePosition = position;
                provinceName = provinceList.get(position);
                // 获取当前省份对应的城市list
                cityList.clear();
                List<Province.CityBean> cityBeans = provinces.get(position).getCity();
                for (Province.CityBean city : cityBeans) {
                    cityList.add(city.getName());
                }

                // 刷新城市列表
                spCity.setSelection(0);

                cityName = cityList.get(0);
                cityAdapter.notifyDataSetChanged();

                // 刷新城区列表
                updateArea(0);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // 显示城市数据
        spCity.setAdapter(cityAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item, cityList));
        spCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cityPosition = position;
                cityName = cityList.get(position);

                // 刷新城区列表
                updateArea(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // 显示城区数据
        spArea.setAdapter(areaAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, areaList));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                areaName = areaList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }








    /**
     * 更新城区数据
     *
     * @param position
     */
    private void updateArea(int position) {
        areaList.clear();
        Province.CityBean cityBean = provinces.get(provincePosition).getCity().get(position);
        areaList.addAll(cityBean.getArea());
        spArea.setSelection(0);
        areaName = areaList.get(0);
        areaAdapter.notifyDataSetChanged();
    }

/*    private void setInitSp(){
        setSpinnerItemSelectedByValue(spProvince,"福建省");
        setSpinnerItemSelectedByValue(spCity,"厦门市");
        setSpinnerItemSelectedByValue(spArea,"湖里区");

    }*/


    /**
     * 根据值, 设置spinner默认选中:
     * @param spinner
     * @param value
     */
    public void setSpinnerItemSelectedByValue(Spinner spinner,String value){
        SpinnerAdapter apsAdapter= spinner.getAdapter(); //得到SpinnerAdapter对象
        int k= apsAdapter.getCount();
        for(int i=0;i<k;i++){
            if(value.equals(apsAdapter.getItem(i).toString())){
                spinner.setSelection(i,true);// 默认选中项
                break;
            }
        }
    }


    /**
     * 从assert文件夹中获取json数据
     */
    private void initJsonData() {


    }

    private void getJson(){
        Gson gson = new Gson();
        provinces  = gson.fromJson(AssetUtils.getJson(this, "citylist.json"), new TypeToken<Map<String, Province>>() {
        }.getType());
        showData();



    }


    @Override
    public void getUrl(SelectCityData selectCityData) {
        tvSelectCity.setText((provinceName.equals(cityName) ? "" : provinceName+" ") + cityName +" "+ areaName);
        String s = tvSelectCity.getText().toString();
        UserManager.getInstance().saveCity(s);
        UserManager.getInstance().saveUrl(selectCityData.getApiUrl());
        UserManager.getInstance().saveImageUrl(selectCityData.getOssUrl());
        startActivity(LoginActivity.class);
    }

    @Override
    public void getAreaData(List<AreaInfo> list) {

    }





/*
    //打开定位和存储权限
    private void openPower(){
        if((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED)||ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED){
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1311);
            //String数组中为申请的权限，第一个是相机，第二个为修改内存，最后的参数即为申请授权的返回值，我设置的1311
        }
    } */

    //打开定位和存储权限
    private void openPower(){
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {

            // 已经申请过权限，做想做的事
        } else {
            // 没有申请过权限，现在去申请
            EasyPermissions.requestPermissions(this, "打开定位,相机，存储权限",
                    APIUrls.COMMON_CONFIG.PERMISSIONS_CODE, perms);
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        //请求成功执行相应的操作
        /*switch (requestCode){
            case 0:
                Toast.makeText(this, "已获取WRITE_EXTERNAL_STORAGE权限", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                Toast.makeText(this, "已获取WRITE_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限", Toast.LENGTH_SHORT).show();
                break;
        }*/
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
           //无权限，且被选择"不再提醒"：提醒客户到APP应用设置中打开权限
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            makeToast("拒绝权限，不再弹出询问框，请前往APP应用设置中打开此权限");
        } else {//无权限，只是单纯被拒绝
            makeToast( "拒绝权限，等待下次询问哦");
        }
    }
}
